import * as types from '../mutation-types'
import http from '@/utils/http'
import { SERVER_URL } from '@/config'
import {getToken, setToken, removeToken} from '@/utils/helpers'
export default {
  state: {
    token: getToken(),
    userInfo: null,
    unreadMessage: 0
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    unreadMessage: state => state.unreadMessage,
    permissions: state => {
      if (state.userInfo && state.userInfo.permissions) {
        return state.userInfo.permissions
      } else {
        return []
      }
    },
    routers: state => state.routers,
    accessedRouters: state => state.accessedRouters
  },
  mutations: {
    [types.SET_TOKEN]: (state, token) => {
      setToken(token)
      state.token = token
    },
    [types.SET_USER_INFO]: (state, userInfo) => {
      state.userInfo = userInfo
    },
    [types.SET_UNREAD_MESSAGE]: (state, count) => {
      state.unreadMessage = count
    }
  },
  actions: {
    loginByPassword: ({ commit }, account) => {
      return new Promise((resolve, reject) => {
        http.post('/auth', account).then(response => {
          commit(types.SET_TOKEN, response.data.access_token)
          resolve()
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    logout: ({commit, state}) => {
      return new Promise((resolve, reject) => {
        http.post('/logout', state.token).then(() => {
          commit(types.SET_TOKEN, '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserInfo: ({commit, state}) => {
      return new Promise((resolve, reject) => {
        http.get('/user').then(response => {
          commit(types.SET_USER_INFO, response.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUnreadMessage: ({commit}, toUserId) => {
      let source = new EventSource(SERVER_URL + '/api/chats/count/' + toUserId)
      source.onmessage = function (e) {
        commit(types.SET_UNREAD_MESSAGE, parseInt(e.data))
      }
    }
  }
}
